/*
 * Copyright 2008 The Brui Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.googlecode.brui.beans;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Provides convenient reflective access to the properties of a Java bean.
 * 
 * @author Nathan C Jones
 */
public final class Bean {

	/** The wrapped bean object. */
	private final Object javaBean;

	/** The properties extracted from the bean. */
	private final Map<String, Property> properties;

	/**
	 * Create a new {@link Bean} which can access the bean properties of the
	 * given object.
	 * 
	 * @param bean the bean object to wrap.
	 * @throws NullPointerException if the bean is <code>null</code>.
	 */
	public Bean(final Object bean) {
		if (bean == null) {
			throw new NullPointerException();
		}
		this.javaBean = bean;
		properties = new HashMap<String, Property>();
		initProperties();
	}

	private void initProperties() {
		for (final PropertyDescriptor propertyDescriptor : getBeanInfo().getPropertyDescriptors()) {
			if (!"class".equals(propertyDescriptor.getName())) {
				// TODO create a property according to the property type and add it
				// to the map
				// properties.put(propertyDescriptor.getName(), property);
			}
		}
	}

	/**
	 * @return the names of all the bean properties.
	 */
	public List<Property> getProperties() {
		return new ArrayList<Property>(properties.values());
	}

	Object getJavaBean() {
		return javaBean;
	}

	BeanInfo getBeanInfo() {
		try {
			return Introspector.getBeanInfo(getJavaBean().getClass());
		} catch (final IntrospectionException e) {
			throw new RuntimeException(e);
		}
	}

	Class<?> getType() {
		return getJavaBean().getClass();
	}
}
